﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using ST.Common.Util.Security;
using System;
using System.Collections.Generic;
using System.Text;

namespace ST.Common.Util.Model
{
	/// <summary>
	/// 用户会话扩展信息
	/// </summary>
	public partial class UserSession : UserSessionBase
	{
		/// <summary>
		/// 用户登录账号
		/// </summary>
		public string UserCode { get; set; }

		///// <summary>
		///// 当前的AppID
		///// </summary>
		//public string AppID { get; set; }

		/// <summary>
		/// OAuth授权的UnionID
		/// </summary>
		public string UnionID { get; set; }

		/// <summary>
		/// 最后访问的时间戳
		/// </summary>
		public long Timestamp { get; set; }

		///// <summary>
		///// access_token（至少要保留512个字符空间）
		///// </summary>
		//public string AccessToken { get; set; }

		///// <summary>
		///// refresh_token（refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权）
		///// </summary>
		//public string RefreshToken { get; set; }

		/// <summary>
		/// 用户帐户状态
		/// </summary>
		public int State { get; set; }

		/// <summary>
		/// 用户头像
		/// </summary>
		public string Avatar { get; set; }

		/// <summary>
		/// 上次登录时间
		/// </summary>
		public string LastLoginDate { get; set; }

		/// <summary>
		/// 上次登录IP
		/// </summary>
		public string LastLoginIP { get; set; }

		/// <summary>
		/// 写入到响应的cookie里，并返回加密后的skey
		/// </summary>
		/// <param name="response"></param>
		/// <returns></returns>
		public virtual string WriteToResponseCookie(HttpRequest request, HttpResponse response)
		{
			string authSessionBase64Str = EncryptHelper.AESEncrypt(ToJson(), UserCode, Timestamp);
			CookieOptions opts = new CookieOptions();
			opts.Path = request.PathBase.HasValue ? request.PathBase.Value : "/";
			opts.HttpOnly = true;//安全性高，客户端不能通过document.cookie访问
			response.Cookies.Append("skey", authSessionBase64Str, opts);
			response.Cookies.Append("ucode", UserCode, opts);
			return authSessionBase64Str;
		}
	}
}
